import {CacheFirst, NetworkFirst, StaleWhileRevalidate} from 'workbox-strategies';
import {registerRoute} from "workbox-routing";
import {CacheableResponsePlugin} from "workbox-cacheable-response";
import {ExpirationPlugin} from "workbox-expiration";
import {BroadcastUpdatePlugin} from "workbox-broadcast-update";
import {precacheAndRoute} from "workbox-precaching";

//precache
precacheAndRoute(self.__WB_MANIFEST||[]);

// html resources
registerRoute(({request}) => request.destination === 'document',
  new NetworkFirst({
    cacheName: 'blog-html',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200]
      })
    ]
  })
);

// styles
registerRoute(({request}) => request.destination === 'style',
  new StaleWhileRevalidate({
    cacheName: 'blog-css',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200]
      }),
      new BroadcastUpdatePlugin({
        headersToCheck: ['ETag']
      })
    ]
  })
);

// js
registerRoute(({request}) => request.destination === 'script',
  new NetworkFirst({
    cacheName: 'blog-js',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200]
      })
    ]
  })
);

// google font style
registerRoute(new RegExp('https://fonts\.googleapis\.com/'),
  new StaleWhileRevalidate({
    cacheName: 'google-fonts-stylesheets',
  }),
);

// google font
registerRoute(new RegExp('https://fonts\.gstatic\.com/'),
  new CacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 365 * 24 * 60 * 60,
        maxEntries: 30,
      })
    ],
  }),
);

// image from any where
registerRoute(({request}) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'blog-image',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 30 * 24 * 60 * 60,
        maxEntries: 60,
      }),
    ],
  }),
);

self.skipWaiting();